#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

// ==================== 抽象层接口定义 ====================

// 事件类型抽象
typedef enum {
    EVENT_NONE = 0,
    EVENT_TIMER,
    EVENT_KEY_INPUT,
    EVENT_NETWORK,
    EVENT_SENSOR,
    EVENT_USER_DEFINED,
    EVENT_MAX_TYPES
} EventType;

// 事件抽象接口
typedef struct {
    EventType type;
    int id;
    void* data;
    size_t data_len;
    unsigned long timestamp;
    int priority;  // 事件优先级
} IEvent;

// 事件处理器抽象接口
typedef void (*IEventHandler)(IEvent event);

// 任务状态
typedef enum {
    TASK_READY,
    TASK_RUNNING,
    TASK_WAITING,
    TASK_FINISHED
} TaskState;

// 任务抽象接口
typedef struct {
    char name[32];
    IEventHandler handler;
    EventType subscribed_events[EVENT_MAX_TYPES];
    int event_count;
    TaskState state;
    int enabled;
    unsigned long last_run_time;
    unsigned long run_interval;  // 运行间隔(ms)
    void* task_data;  // 任务私有数据
} ITask;

// 调度器抽象接口
typedef struct {
    int (*init)(void);
    int (*start)(void);
    int (*stop)(void);
    int (*run_cycle)(void);  // 单次调度循环
    int (*publish_event)(IEvent event);
    int (*subscribe_task)(ITask* task, EventType event_type);
    int (*unsubscribe_task)(ITask* task, EventType event_type);
    void (*get_stats)(void);
} IScheduler;

// 事件队列抽象接口
typedef struct {
    int (*push)(IEvent event);
    int (*pop)(IEvent* event);
    int (*get_size)(void);
    int (*get_capacity)(void);
    void (*cleanup)(void);
} IEventQueue;

// ==================== 具体实现层 ====================

// 事件队列节点
typedef struct EventNode {
    IEvent event;
    struct EventNode* next;
} EventNode;

// 事件队列具体实现
typedef struct {
    EventNode* front;
    EventNode* rear;
    int count;
    int max_size;
} ConcreteEventQueue;

static ConcreteEventQueue g_concrete_queue;

// 任务注册表项
typedef struct {
    EventType type;
    IEventHandler handler;
    char task_name[32];
} TaskRegistryEntry;

// 调度器具体实现
typedef struct {
    TaskRegistryEntry registry[EVENT_MAX_TYPES];
    int registry_count;
    int running;
    int processed_events;
    int dropped_events;
    unsigned long cycle_count;
    ITask* tasks[10];  // 支持最多10个任务
    int task_count;
} ConcreteScheduler;

static ConcreteScheduler g_concrete_scheduler;

// ==================== 时间片轮询调度器 ====================

// 获取当前时间(毫秒)
unsigned long get_current_time_ms(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}

// 事件队列具体实现
int event_queue_push_impl(IEvent event) {
    if (g_concrete_queue.count >= g_concrete_queue.max_size) {
        g_concrete_scheduler.dropped_events++;
        return -1;
    }
    
    EventNode* new_node = (EventNode*)malloc(sizeof(EventNode));
    if (!new_node) {
        return -1;
    }
    
    // 复制事件数据
    new_node->event = event;
    if (event.data != NULL && event.data_len > 0) {
        new_node->event.data = malloc(event.data_len);
        if (new_node->event.data) {
            memcpy(new_node->event.data, event.data, event.data_len);
        }
    }
    
    new_node->next = NULL;
    
    if (g_concrete_queue.rear == NULL) {
        g_concrete_queue.front = g_concrete_queue.rear = new_node;
    } else {
        g_concrete_queue.rear->next = new_node;
        g_concrete_queue.rear = new_node;
    }
    
    g_concrete_queue.count++;
    return 0;
}

int event_queue_pop_impl(IEvent* event) {
    if (g_concrete_queue.front == NULL) {
        return -1;
    }
    
    EventNode* temp = g_concrete_queue.front;
    *event = temp->event;
    
    g_concrete_queue.front = g_concrete_queue.front->next;
    if (g_concrete_queue.front == NULL) {
        g_concrete_queue.rear = NULL;
    }
    
    g_concrete_queue.count--;
    free(temp);
    return 0;
}

int event_queue_get_size_impl(void) {
    return g_concrete_queue.count;
}

int event_queue_get_capacity_impl(void) {
    return g_concrete_queue.max_size;
}

void event_queue_cleanup_impl(void) {
    EventNode* current = g_concrete_queue.front;
    while (current != NULL) {
        EventNode* next = current->next;
        if (current->event.data != NULL) {
            free(current->event.data);
        }
        free(current);
        current = next;
    }
    
    g_concrete_queue.front = g_concrete_queue.rear = NULL;
    g_concrete_queue.count = 0;
}

// ==================== 调度器具体实现 ====================

int scheduler_init_impl(void) {
    memset(&g_concrete_scheduler, 0, sizeof(ConcreteScheduler));
    g_concrete_scheduler.running = 0;
    g_concrete_scheduler.processed_events = 0;
    g_concrete_scheduler.dropped_events = 0;
    g_concrete_scheduler.cycle_count = 0;
    
    // 初始化事件队列
    memset(&g_concrete_queue, 0, sizeof(ConcreteEventQueue));
    g_concrete_queue.max_size = 100;
    
    printf("[Scheduler] Initialized with time-slice polling\n");
    printf("[Scheduler] Queue capacity: %d\n", g_concrete_queue.max_size);
    return 0;
}

int scheduler_publish_event_impl(IEvent event) {
    if (event.timestamp == 0) {
        event.timestamp = get_current_time_ms();
    }
    
    int result = event_queue_push_impl(event);
    if (result == 0) {
        printf("[Scheduler] Event published: type=%d, id=%d, priority=%d\n", 
               event.type, event.id, event.priority);
    } else {
        printf("[Scheduler] Failed to publish event: type=%d, id=%d\n", 
               event.type, event.id);
    }
    
    return result;
}

int scheduler_subscribe_task_impl(ITask* task, EventType event_type) {
    if (g_concrete_scheduler.registry_count >= EVENT_MAX_TYPES) {
        printf("[Scheduler] Registry full, cannot subscribe\n");
        return -1;
    }
    
    // 检查是否已注册
    for (int i = 0; i < g_concrete_scheduler.registry_count; i++) {
        if (g_concrete_scheduler.registry[i].type == event_type) {
            printf("[Scheduler] Event type %d already registered\n", event_type);
            return -1;
        }
    }
    
    // 注册新的事件处理器
    g_concrete_scheduler.registry[g_concrete_scheduler.registry_count].type = event_type;
    g_concrete_scheduler.registry[g_concrete_scheduler.registry_count].handler = task->handler;
    strncpy(g_concrete_scheduler.registry[g_concrete_scheduler.registry_count].task_name, 
            task->name, 31);
    g_concrete_scheduler.registry_count++;
    
    printf("[Scheduler] Task '%s' subscribed to event type %d\n", task->name, event_type);
    return 0;
}

int scheduler_unsubscribe_task_impl(ITask* task, EventType event_type) {
    for (int i = 0; i < g_concrete_scheduler.registry_count; i++) {
        if (g_concrete_scheduler.registry[i].type == event_type && 
            strcmp(g_concrete_scheduler.registry[i].task_name, task->name) == 0) {
            // 移除注册项
            for (int j = i; j < g_concrete_scheduler.registry_count - 1; j++) {
                g_concrete_scheduler.registry[j] = g_concrete_scheduler.registry[j + 1];
            }
            g_concrete_scheduler.registry_count--;
            printf("[Scheduler] Task '%s' unsubscribed from event type %d\n", task->name, event_type);
            return 0;
        }
    }
    return -1;
}

// 注册任务到调度器
int scheduler_register_task(ITask* task) {
    if (g_concrete_scheduler.task_count >= 10) {
        printf("[Scheduler] Task list full, cannot register\n");
        return -1;
    }
    
    g_concrete_scheduler.tasks[g_concrete_scheduler.task_count] = task;
    g_concrete_scheduler.task_count++;
    
    printf("[Scheduler] Task '%s' registered\n", task->name);
    return 0;
}

// 单次调度循环
int scheduler_run_cycle_impl(void) {
    if (!g_concrete_scheduler.running) {
        return -1;
    }
    
    g_concrete_scheduler.cycle_count++;
    unsigned long current_time = get_current_time_ms();
    
    // 1. 处理事件队列
    IEvent event;
    while (event_queue_pop_impl(&event) == 0) {
        printf("[Scheduler] Processing event: type=%d, id=%d\n", event.type, event.id);
        
        // 查找对应的任务处理器
        IEventHandler handler = NULL;
        for (int i = 0; i < g_concrete_scheduler.registry_count; i++) {
            if (g_concrete_scheduler.registry[i].type == event.type) {
                handler = g_concrete_scheduler.registry[i].handler;
                break;
            }
        }
        
        if (handler != NULL) {
            handler(event);
            g_concrete_scheduler.processed_events++;
        } else {
            printf("[Scheduler] No handler for event type %d\n", event.type);
        }
        
        // 清理事件数据
        if (event.data != NULL) {
            free(event.data);
        }
    }
    
    // 2. 时间片轮询执行任务
    for (int i = 0; i < g_concrete_scheduler.task_count; i++) {
        ITask* task = g_concrete_scheduler.tasks[i];
        
        if (task->enabled && task->state == TASK_READY) {
            // 检查是否到达运行时间
            if (current_time - task->last_run_time >= task->run_interval) {
                task->state = TASK_RUNNING;
                
                // 模拟任务执行（这里简化处理，实际应该调用任务的主函数）
                printf("[Scheduler] Running task: %s\n", task->name);
                
                task->last_run_time = current_time;
                task->state = TASK_READY;
            }
        }
    }
    
    return 0;
}

int scheduler_start_impl(void) {
    if (g_concrete_scheduler.running) {
        printf("[Scheduler] Scheduler already running\n");
        return -1;
    }
    
    g_concrete_scheduler.running = 1;
    printf("[Scheduler] Time-slice polling scheduler started\n");
    return 0;
}

int scheduler_stop_impl(void) {
    if (!g_concrete_scheduler.running) {
        return -1;
    }
    
    g_concrete_scheduler.running = 0;
    printf("[Scheduler] Scheduler stopped\n");
    return 0;
}

void scheduler_get_stats_impl(void) {
    printf("\n=== Time-Slice Polling Scheduler Statistics ===\n");
    printf("Cycle count: %lu\n", g_concrete_scheduler.cycle_count);
    printf("Processed events: %d\n", g_concrete_scheduler.processed_events);
    printf("Dropped events: %d\n", g_concrete_scheduler.dropped_events);
    printf("Queue size: %d/%d\n", event_queue_get_size_impl(), event_queue_get_capacity_impl());
    printf("Registered handlers: %d\n", g_concrete_scheduler.registry_count);
    printf("Registered tasks: %d\n", g_concrete_scheduler.task_count);
    printf("===============================================\n");
}

// ==================== 抽象接口实例化 ====================

// 事件队列抽象接口实例
static IEventQueue EventQueue = {
    .push = event_queue_push_impl,
    .pop = event_queue_pop_impl,
    .get_size = event_queue_get_size_impl,
    .get_capacity = event_queue_get_capacity_impl,
    .cleanup = event_queue_cleanup_impl
};

// 调度器抽象接口实例
static IScheduler Scheduler = {
    .init = scheduler_init_impl,
    .start = scheduler_start_impl,
    .stop = scheduler_stop_impl,
    .run_cycle = scheduler_run_cycle_impl,
    .publish_event = scheduler_publish_event_impl,
    .subscribe_task = scheduler_subscribe_task_impl,
    .unsubscribe_task = scheduler_unsubscribe_task_impl,
    .get_stats = scheduler_get_stats_impl
};

// ==================== 具体任务实现 ====================

// 定时器事件处理函数
void timer_event_handler(IEvent event) {
    printf("[TimerTask] Handling timer event %d (priority: %d)\n", event.id, event.priority);
    printf("[TimerTask] Performing periodic task at %lu...\n", event.timestamp);
}

// 键盘输入事件处理函数  
void key_input_handler(IEvent event) {
    printf("[KeyInputTask] Handling key input event %d\n", event.id);
    
    if (event.data != NULL) {
        printf("[KeyInputTask] Key pressed: %s\n", (char*)event.data);
    }
    
    printf("[KeyInputTask] Processing user input...\n");
}

// 网络事件处理函数
void network_event_handler(IEvent event) {
    printf("[NetworkTask] Handling network event %d\n", event.id);
    
    if (event.data != NULL) {
        printf("[NetworkTask] Received data: %s\n", (char*)event.data);
    }
    
    printf("[NetworkTask] Processing network packet...\n");
}

// 传感器事件处理函数
void sensor_event_handler(IEvent event) {
    printf("[SensorTask] Handling sensor event %d\n", event.id);
    
    if (event.data != NULL) {
        int sensor_value = *(int*)event.data;
        printf("[SensorTask] Sensor value: %d\n", sensor_value);
        
        if (sensor_value > 50) {
            printf("[SensorTask] High value detected! Taking action...\n");
        }
    }
}

// 事件生产者任务数据
typedef struct {
    int event_id;
    unsigned long last_produce_time;
} ProducerData;

// 事件生产者任务函数
void event_producer_task(ITask* task) {
    ProducerData* data = (ProducerData*)task->task_data;
    unsigned long current_time = get_current_time_ms();
    
    if (current_time - data->last_produce_time >= 2000) { // 每2秒产生一个事件
        // 产生不同类型的事件
        IEvent event;
        event.id = data->event_id++;
        event.timestamp = current_time;
        event.data = NULL;
        event.data_len = 0;
        
        // 轮询不同类型的事件
        switch (event.id % 4) {
            case 0:
                event.type = EVENT_TIMER;
                event.priority = 1;
                printf("[Producer] Generated timer event %d\n", event.id);
                break;
            case 1:
                event.type = EVENT_KEY_INPUT;
                event.priority = 2;
                {
                    char* key_data = "Enter Key";
                    event.data_len = strlen(key_data) + 1;
                    event.data = key_data;
                }
                printf("[Producer] Generated key input event %d\n", event.id);
                break;
            case 2:
                event.type = EVENT_NETWORK;
                event.priority = 3;
                {
                    char* net_data = "Network Packet";
                    event.data_len = strlen(net_data) + 1;
                    event.data = net_data;
                }
                printf("[Producer] Generated network event %d\n", event.id);
                break;
            case 3:
                event.type = EVENT_SENSOR;
                event.priority = 1;
                {
                    int sensor_value = rand() % 100;
                    event.data_len = sizeof(int);
                    event.data = &sensor_value;
                }
                printf("[Producer] Generated sensor event %d\n", event.id);
                break;
        }
        
        Scheduler.publish_event(event);
        data->last_produce_time = current_time;
    }
}

// 系统监控任务函数
void system_monitor_task(ITask* task) {
    static unsigned long last_report_time = 0;
    unsigned long current_time = get_current_time_ms();
    
    if (current_time - last_report_time >= 5000) { // 每5秒报告一次
        printf("[Monitor] System running...\n");
        last_report_time = current_time;
    }
}

// ==================== 应用层代码 ====================

int main(void) {
    printf("Starting Time-Slice Polling Event-Driven System...\n");
    
    // 初始化调度器
    Scheduler.init();
    
    // 创建并注册任务
    ITask timer_task = {
        .name = "TimerTask",
        .handler = timer_event_handler,
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 1000,  // 1秒间隔
        .task_data = NULL
    };
    
    ITask key_input_task = {
        .name = "KeyInputTask", 
        .handler = key_input_handler,
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 500,   // 500ms间隔
        .task_data = NULL
    };
    
    ITask network_task = {
        .name = "NetworkTask",
        .handler = network_event_handler,
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 800,   // 800ms间隔
        .task_data = NULL
    };
    
    ITask sensor_task = {
        .name = "SensorTask",
        .handler = sensor_event_handler,
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 1200,  // 1.2秒间隔
        .task_data = NULL
    };
    
    // 创建事件生产者任务
    ProducerData producer_data = {
        .event_id = 0,
        .last_produce_time = 0
    };
    
    ITask producer_task = {
        .name = "EventProducer",
        .handler = NULL,  // 这个任务有自定义的处理函数
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 100,   // 100ms检查一次
        .task_data = &producer_data
    };
    
    // 创建系统监控任务
    ITask monitor_task = {
        .name = "SystemMonitor",
        .handler = NULL,  // 这个任务有自定义的处理函数
        .state = TASK_READY,
        .enabled = 1,
        .last_run_time = 0,
        .run_interval = 500,   // 500ms检查一次
        .task_data = NULL
    };
    
    // 订阅事件
    Scheduler.subscribe_task(&timer_task, EVENT_TIMER);
    Scheduler.subscribe_task(&key_input_task, EVENT_KEY_INPUT);
    Scheduler.subscribe_task(&network_task, EVENT_NETWORK);
    Scheduler.subscribe_task(&sensor_task, EVENT_SENSOR);
    
    // 注册任务到调度器
    scheduler_register_task(&timer_task);
    scheduler_register_task(&key_input_task);
    scheduler_register_task(&network_task);
    scheduler_register_task(&sensor_task);
    scheduler_register_task(&producer_task);
    scheduler_register_task(&monitor_task);
    
    // 启动调度器
    Scheduler.start();
    
    printf("Time-slice polling event-driven system started successfully\n");
    printf("Using time-slice polling instead of pthread\n");
    printf("Total registered tasks: %d\n", g_concrete_scheduler.task_count);
    
    // 主调度循环
    int run_seconds = 20;  // 运行20秒
    unsigned long start_time = get_current_time_ms();
    unsigned long last_cycle_time = start_time;
    
    while (get_current_time_ms() - start_time < run_seconds * 1000) {
        // 执行单次调度循环
        Scheduler.run_cycle();
        
        // 手动执行生产者任务（模拟时间片）
        event_producer_task(&producer_task);
        
        // 手动执行监控任务
        system_monitor_task(&monitor_task);
        
        // 控制循环频率，避免CPU占用过高
        usleep(10000);  // 10ms延迟，模拟时间片
        
        // 每5秒显示一次统计信息
        if (get_current_time_ms() - last_cycle_time >= 5000) {
            Scheduler.get_stats();
            last_cycle_time = get_current_time_ms();
        }
    }
    
    // 清理资源
    printf("Shutting down system...\n");
    Scheduler.stop();
    EventQueue.cleanup();
    
    printf("Final statistics:\n");
    Scheduler.get_stats();
    printf("System shutdown complete\n");
    
    return 0;
}